package com.chinanet.oracle.service;

import com.chinanet.auth.JwtTokenUtil;
import com.chinanet.oracle.repository.UserRepository;
import com.chinanet.oracle.service.imp.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

    @Qualifier("loginAuthenticationManager")
    @Autowired
    private AuthenticationManager authenticationManager;

    @Qualifier("jwtUserDetailsService")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserRepository userRepository;


    @Override
    public String login(String account, String password) {
        System.out.println("Login");
        System.out.println("UsernamePasswordAuthenticationToken封装");
        // 将用户名和密码进行封装
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(account, password);
        System.out.println("authentication");
        System.out.println(account+":"+password);
        // 认证
        Authentication authentication = authenticationManager.authenticate(upToken);
        // 认证成功，建立安全上下文
        System.out.println("认证成功，建立安全上下文");
        SecurityContextHolder.getContext().setAuthentication(authentication);
        System.out.println("生成用户信息");
        UserDetails userDetails = userDetailsService.loadUserByUsername(account);
        System.out.println("生成Token");
        return jwtTokenUtil.generateToken(userDetails);
    }
    @Override
    public String refreshToken(String oldToken) {
        String token = oldToken.substring("Bearer ".length());
        if (!jwtTokenUtil.isTokenExpired(token)) {
            return jwtTokenUtil.refreshToken(token);
        }
        return "error";
    }

}